package com.ysu.shop.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.ysu.shop.exception.MyException;
import com.ysu.shop.pojo.User;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;

public class JwtUtil {

    /**
     * 过期时间为1天
     */
    private static final long EXPIRE_TIME = 24*60*60*1000;


    /**
     * token私钥
     */
    public static final String KEY = "ysu_user_shop";


    public static String create(User user) {

        HashMap<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        return JWT.create()
                .withHeader(header)
                .withClaim("id", user.getId())
                .withClaim("username",user.getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .sign(Algorithm.HMAC256(KEY));
    }

    public static boolean isExpire(String token){
        return System.currentTimeMillis() - JWT.decode(token).getExpiresAt().getTime() > 0 ;
    }


    public static int getUserId(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        return JWT.decode(token).getClaim("id").asInt();
    }


}